//
//  WBWelcomeView.swift
//  weiboswift
//
//  Created by dingzhibing on 2017/8/1.
//  Copyright © 2017年 dingzhibing. All rights reserved.
//

import UIKit
import SDWebImage
/// 欢迎视图
class WBWelcomeView: UIView {
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var bottomCons: NSLayoutConstraint!
    @IBOutlet weak var iconViewWidthConstraint: NSLayoutConstraint!
    class func welcomeView() -> WBWelcomeView{
        let nib = UINib(nibName: "WBWelcomeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomeView
        
        //从xib加载的视图默认是600*600
        v.frame = UIScreen.main.bounds
        return v
    }
    
    /// 自动布局系统更新完成约束后，会自动调用此方法
    /// 通常是对自视图布局进行修改
//    override func layoutSubviews() {
//        <#code#>
//    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        // 提示 initWithCoder 只是刚刚从Xib的二进制文件将视图数据加载完成
        // 还没有和代码连线建立起关系，开发时，千万不要在这个方法中处理ui
        // iconView为nil
        print("initWithCoder + \(iconView)")
    }
    
    override func awakeFromNib() {
        print("awakeFromNib + \(iconView)")
        
        // 1. url
        guard let urlString = WBNetworkManager.shared.userAccount.avatar_large ,
            let url = URL(string:urlString)
        else {
            
            return
        }
        // 2. 设置头像
        // 如果网络图像没有下载完成，显示展位图像
        
        iconView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big"))
        iconView.layer.cornerRadius = iconViewWidthConstraint.constant*0.5//42.5
        iconView.layer.masksToBounds = true
        //iconView.layer.cornerRadius    用xib keypath设置
        //iconView.layer.masksToBounds
    }
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        
        //layoutIfNeeded 会按照当前的约束直接更新控件位置
        //执行之后，控件所在位置就是xib中布局位置
        self.layoutIfNeeded()
        
        bottomCons.constant = bounds.size.height - 200
        
        //如果控件的frame还没有计算好，所有约束会一起动画
        UIView.animate(withDuration: 1.0,
                       delay: 0,
                       usingSpringWithDamping: 0.7,
                       initialSpringVelocity: 0, options: [], animations: {
                        //更新约束
                        self.layoutIfNeeded()
        }) { (_) in
            UIView.animate(withDuration: 1.0, animations: { 
                self.tipLabel.alpha = 1
            })
            UIView.animate(withDuration: 1.0, animations: { 
                self.tipLabel.alpha = 1
            }, completion: { (_) in
                self.removeFromSuperview()
            })
        }
    }
}
